package com.aiseminar.aispeaker.reader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

/**
 * Created by rdc-hankang on 6/21/15.
 */
public class BookReader {
    private static final String gb2312 = "GB2312";
    private static final String utf8 = "UTF-8";
    private static final String defaultCode = gb2312;
    private static final int sizePerPage = 500;

    private String mFilePath;
    private long mFileSize = 0;
    private int mPageCount;

    public BookReader(String path) {
        mFilePath = path;
        File file = new File(mFilePath);
        if (file.exists()) {
            try {
                FileInputStream fInputStream = new FileInputStream(mFilePath);
                InputStreamReader inputStreamReader = new InputStreamReader(fInputStream, defaultCode);
                BufferedReader in = new BufferedReader(inputStreamReader, sizePerPage);

                mFileSize = 0;
                mPageCount = 0;
                while (in.ready()) {
                    long skipNum = in.skip(sizePerPage);
                    if (skipNum <= 0) {
                        break;
                    }

                    mPageCount ++;
                    mFileSize += skipNum;
                    if (skipNum < sizePerPage) {
                        break;
                    }
                }

                in.close();
                inputStreamReader.close();
                fInputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public int getPageCount() {
        return mPageCount;
    }

    public String getContentInPage(int pageNum) {
        return getStringFromFile(defaultCode, pageNum);
    }

    public String getStringFromFile(String code, int pageNum) {
        try {
            if (! new File(mFilePath).exists()) {
                return null;
            }

            FileInputStream fInputStream = new FileInputStream(mFilePath);
            InputStreamReader inputStreamReader = new InputStreamReader(fInputStream, code);
            BufferedReader in = new BufferedReader(inputStreamReader, sizePerPage);

//            StringBuffer sBuffer = new StringBuffer();
            char[] cBuffer = new char[sizePerPage + 1];
//            while (in.ready()) {
//                sBuffer.append(in.readLine() + "\n");
//            }

            if (in.ready()) {
                long skipNum = in.skip((pageNum - 1) * sizePerPage);
                in.read(cBuffer, 0, sizePerPage);
            }
            in.close();
            inputStreamReader.close();
            fInputStream.close();

            return new String(cBuffer);
//            return sBuffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
